package com.yuncheng.system.sysconfig;

import com.yuncheng.system.sysconfig.entity.SysConfig;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class SyncSysconfigAspect implements ApplicationContextAware {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private ApplicationContext applicationContext;

    private void notifySysConfigChanged(JoinPoint joinPoint) {
        if (null != this.applicationContext) {
            SysConfig sysConfig = null;

            Object[] args = joinPoint.getArgs();
            if ((null != args) && (args.length > 0) && (null != args[0]) && (args[0] instanceof SysConfig)) {
                sysConfig = (SysConfig) args[0];
            }

            logger.info("-----notifySysConfigChanged publishEvent configCode=" + ((null != sysConfig) ? sysConfig.getConfigCode() : null) + "-----");
            this.applicationContext.publishEvent(
                    new SysConfigChangedEvent(this.applicationContext,
                            (null != sysConfig) ? sysConfig.getConfigCode() : null)
            );
        }
    }

    @AfterReturning("execution(* com.yuncheng.system.sysconfig.service.impl.SysConfigServiceImpl.updateById(..))")
    public void doUpdateByIdReturning(JoinPoint joinPoint) {
        logger.info("-----doUpdateByIdReturning-----");
        notifySysConfigChanged(joinPoint);
    }

    @AfterReturning("execution(* com.yuncheng.system.sysconfig.service.impl.SysConfigServiceImpl.save(..))")
    public void doSaveReturning(JoinPoint joinPoint) {
        logger.info("-----doSaveReturning-----");
        notifySysConfigChanged(joinPoint);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
